const http = require('http');
const fs = require('fs');
const path = require('path');
const stream = require('stream');
const url = require('url');

var storePath = 'attachment';
var port = 8080;
var placeholder = '<!-- attachmentlist -->';

http.createServer(function(request, response) {

  var location = url.parse(request.url)
  
  var pathHead = /^(\/[^\/]*)/.exec(location.pathname)[1];
  
  switch (pathHead) {
    case '/upload':
      response.end(''); //jsonp
      break;
    case '/download':
      var fileName = location.pathname.replace(pathHead + '/', '');
      var filePath = path.resolve(storePath, fileName);
      var readStream = fs.createReadStream(filePath);
      var stat = fs.statSync(filePath);
      response.writeHead(200, {
        'Content-Type': 'application/octet-stream',
        'Content-Transfer-Encoding': 'binary',
        'Content-Length': stat.size,
        'Content-Disposition': 'attachment; filename=' + fileName
      });
      readStream.pipe(response);
      break;
    case '/favicon.ico':
      response.end('');
      break;
    case '/':
    default:
      var filePath = path.join(__dirname, 'static.html');

      response.writeHead(200, {
        'Content-Type': 'text/html, charset=utf-8'
        // 'Content-Length': stat.size
      });
      
      var fileList = []
      var files
      
      try {
        files = fs.readdirSync(storePath);
      } catch (e) {
        files = []
      }

      files.forEach(fileName => {
        var filePath = path.resolve(storePath, fileName);
        var stat = fs.statSync(filePath)
        if (stat.isFile()) {
          fileList.push(fileName);
        }
      })
      
      var attachmentlistHTML = ''
      
      fileList.forEach(file => {
        attachmentlistHTML += '<tr><td>'
          + ['<a href="/download/', file, '">', file, '</a>'].join('')
          + '</td></tr>'
      })
      
      var staticText = ''
      
      var readStream = fs.createReadStream(filePath);
      
      readStream.on('readable', () => {
        let chunk;
        
        while (null !== (chunk = readStream.read())) {
          staticText += chunk.toString();
        }
      });
      
      readStream.on('end', () => {
        staticText = staticText.replace(placeholder, attachmentlistHTML)
        var staticStream = new stream.Readable();
        staticStream.push(staticText)
        staticStream.push(null);
        staticStream.pipe(response);
      })
      break;
  }

}).listen(port);

console.log("http server started in port", port);